package com.vrv.netmgr.upgrade;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.webkit.URLUtil;
import android.widget.ProgressBar;

import com.vrv.common.UpdateProgress;

public class LoadApk {
    private static final String TAG = LoadApk.class.getSimpleName();
    private static final boolean DEBUG = true;
	//
    private static final int UPDATE_UI = 1;
	private UpdateProgress dialog;
	private ProgressBar updateBar;
	private int progress = 0;
	private int count = 0;
	private int length = 0;
	//
	public Context mContext;
	public String mApk;
	public String mUrl;
	public String mVersionMsg;

	public LoadApk(Context context, String apk, String url, String versionMsg) {
		this.mContext = context;
		this.mApk = apk;
		this.mUrl = url;
		this.mVersionMsg = versionMsg;
	}
	/**
	 * 更新进度条
	 */
	Handler mHandler = new Handler(){
		public void handleMessage(Message msg){
			switch(msg.what){
			case UPDATE_UI:
				updateBar.setProgress(progress);
				dialog.setText(progress + "%");
				break;
			}
		}
	};

	/**
	 * 下载主框架文件
	 */
	public boolean downMain() {
		if(DEBUG)Log.v(TAG, "download()");

		boolean ret = false;
		//
		if (!checkNetworkState(mContext)) {
			ret = false;
		} else {
			downLoadFile();
			ret = true;
		}
		//
		return ret;
	}

	public static boolean checkNetworkState(Context context) {
		if(DEBUG)Log.v(TAG, "isNetworkAvailable()");
		try {
			ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo info = cm.getActiveNetworkInfo();
			return (info != null && info.isConnected());
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	private void downLoadFile() {
		if(DEBUG)Log.v(TAG, "downLoadFile()");
		try {
			// 开启进度条
			showWaitDialog();
			// 开始下载
			Runnable r = new Runnable() {
				public void run() {
					try {
						File myTempFile = doDownloadTheFile(mUrl, mApk);
						dialog.cancel();
						dialog.dismiss();
						openFile(myTempFile);
					} catch (Exception e) {
						Log.e(TAG, e.getMessage(), e);
						dialog.cancel();
						dialog.dismiss();
					}
				}
			};
			new Thread(r).start();
		} catch (Exception e) {
			e.printStackTrace();
			dialog.cancel();
			dialog.dismiss();
		}
	}

	public void showWaitDialog() {
		if(DEBUG)Log.v(TAG, "showWaitDialog()");
		dialog = new UpdateProgress(mContext);
		updateBar = dialog.progressBar;
	}

	/**
	 * 描述：url下载文件
	 */
	private File doDownloadTheFile(String url, String apk) throws Exception {
		if(DEBUG)Log.v(TAG, "doDownloadTheFile()");
		//
		String apkUrl = url + "/" + apk;
		//
		if (!URLUtil.isNetworkUrl(apkUrl)) {
			Log.i(TAG, "getDataSource() It's a wrong URL!");
		} else {
			URL myURL = new URL(apkUrl);
			URLConnection conn = myURL.openConnection();
			conn.connect();
			//
			length = conn.getContentLength();
			//
			InputStream is = conn.getInputStream();
			if (is == null) {
				throw new RuntimeException("stream is null");
			}
			// 创建临时文件
			String[] apkmsg = apk.split("\\.");
			File myTempFile = File.createTempFile(apkmsg[0], ".apk");
			// 保存文件
			FileOutputStream fos = new FileOutputStream(myTempFile);
			//
			byte buf[] = new byte[128];
			do {
				int numread = is.read(buf);
				count += numread;
				progress = (int)(((float)count/length)*100);
				mHandler.sendEmptyMessage(UPDATE_UI);
				if (numread <= 0) {
					break;
				}
				fos.write(buf, 0, numread);

				if(DEBUG)Log.v(TAG, "doDownloadTheFile()...正在下载...");

			} while (true);
			fos.flush();
			fos.close();
			fos = null;
			//
			Log.i(TAG, "getDataSource() Download  ok...");
			try {
				is.close();
			} catch (Exception ex) {
				Log.e(TAG, "getDataSource() error: " + ex.getMessage(), ex);
			}
			return myTempFile;
		}
		//
		return null;
	}

	private void openFile(File f) {
		if(DEBUG)Log.v(TAG, "openFile()");
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		String type = getMIMEType(f);
		intent.setDataAndType(Uri.fromFile(f), type);
		mContext.startActivity(intent);
	}

	private String getMIMEType(File f) {
		if(DEBUG)Log.v(TAG, "getMIMEType()");
		String type = "";
		String fName = f.getName();
		String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();
		if (end.equals("m4a") || end.equals("mp3") || end.equals("mid") || end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
			type = "audio";
		} else if (end.equals("3gp") || end.equals("mp4")) {
			type = "video";
		} else if (end.equals("jpg") || end.equals("gif") || end.equals("png") || end.equals("jpeg") || end.equals("bmp")) {
			type = "image";
		} else if (end.equals("apk")) {
			type = "application/vnd.android.package-archive";
		} else {
			type = "*";
		}
		if (end.equals("apk")) {
		} else {
			type += "/*";
		}
		return type;
	}
}
